package com.cnswhy.cloud.server.comsumer.consumer.userinfotoken;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.redis.annotation.RedisLock;
import com.cnswhy.cloud.common.redis.model.LockTimeoutStrategy;
import com.cnswhy.cloud.server.common.entity.enumeration.MiniAppType;
import com.cnswhy.cloud.server.common.entity.mq.UserInfoTokenMsg;
import com.cnswhy.cloud.server.comsumer.event.AlipayUserEvent;
import com.cnswhy.cloud.server.core.config.AlipayConfig;
import com.cnswhy.cloud.server.core.entity.AlipayUserInfo;
import com.cnswhy.cloud.server.core.entity.WxUserInfo;
import com.cnswhy.cloud.server.core.service.AlipayUserInfoService;
import com.cnswhy.cloud.server.core.service.WxUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 升级
 */
@Component
@Slf4j
public class AlipayUserTokenConsumer implements AlipayUserEvent {
    @Autowired
    AlipayUserInfoService alipayUserInfoService;
    @Autowired
    WxUserInfoService wxUserInfoService;
    @Override
    public void authToken(UserInfoTokenMsg alipayTokenMsg) {
        if(MiniAppType.ALIPAY.eq(alipayTokenMsg.getMiniAppType())){
            log.info(JSON.toJSONString(alipayTokenMsg));
            if(StringUtils.isBlank(alipayTokenMsg.getUserId())){
                log.error("userId is null");
                return;
            }
            AlipayUserInfo alipayUserInfo = getAlipayUserInfo(alipayTokenMsg.getUserId());
            alipayUserInfo.setAccessToken(alipayTokenMsg.getAccessToken());
            alipayUserInfo.setReExpiresIn(alipayTokenMsg.getReExpiresIn());
            alipayUserInfo.setExpiresIn(alipayTokenMsg.getExpiresIn());
            alipayUserInfo.setRefreshToken(alipayTokenMsg.getRefreshToken());
            alipayUserInfoService.updateById(alipayUserInfo);
            if(StringUtils.isBlank(alipayUserInfo.getNickName())){
                AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL,AlipayConfig.APPID,AlipayConfig.RSA_PRIVATE_KEY,AlipayConfig.FORMAT,AlipayConfig.CHARSET,AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
                AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
                AlipayUserInfoShareResponse response = null;
                try {
                    response = alipayClient.execute(request,alipayUserInfo.getAccessToken());
                    if(response.isSuccess()){
                        alipayUserInfo.setAvatar(response.getAvatar());
                        alipayUserInfo.setCity(response.getCity());
                        alipayUserInfo.setGender(response.getGender());
                        alipayUserInfo.setProvince(response.getProvince());
                        alipayUserInfo.setNickName(response.getNickName());
                        alipayUserInfoService.updateById(alipayUserInfo);
                    }
                } catch (AlipayApiException e) {
                    return;
                }

            }
        }else if(MiniAppType.WX.eq(alipayTokenMsg.getMiniAppType())){
            if(StringUtils.isBlank(alipayTokenMsg.getOpenId())){
                return;
            }
            WxUserInfo wxUserInfo = getWxUserInfo(alipayTokenMsg.getOpenId());
            wxUserInfo.setSessionKey(alipayTokenMsg.getSessionKey());
            wxUserInfo.setUnionId(alipayTokenMsg.getUnionId());
            wxUserInfoService.updateById(wxUserInfo);
        }

    }
    @RedisLock(name = "AlipayUserInfo", waitTime = 10,leaseTime = 60,keys = {"#userId"},lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
    private AlipayUserInfo getAlipayUserInfo(String userId){
        AlipayUserInfo alipayUserInfo = alipayUserInfoService.getOne(Wraps.<AlipayUserInfo>lbQ().eq(AlipayUserInfo::getUserId, userId));
        if(alipayUserInfo == null){
            alipayUserInfo = new AlipayUserInfo();
            alipayUserInfo.setUserId(userId);
            alipayUserInfoService.save(alipayUserInfo);
        }
        return alipayUserInfo;
    }
    @RedisLock(name = "WxUserInfo", waitTime = 10,leaseTime = 60,keys = {"#openId"},lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
    private WxUserInfo getWxUserInfo(String openId){
        WxUserInfo wxUserInfo = wxUserInfoService.getOne(Wraps.<WxUserInfo>lbQ().eq(WxUserInfo::getOpenId, openId));
        if(wxUserInfo == null){
            wxUserInfo = new WxUserInfo();
            wxUserInfo.setOpenId(openId);
            wxUserInfoService.save(wxUserInfo);
        }
        return wxUserInfo;
    }
}
